using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BTSProjectWizard;
using System.IO;
using System.Xml;

namespace WizardCreator
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            LoadTree();
        }

        private void LoadTree()
        {
            treeView1.Nodes.Clear();
            string path = Util.GetWizardDir();
            List<WizardInfo> wizards = GetWizards(path);
            TreeNode tn;
            foreach (WizardInfo wi in wizards)
            {
                tn = treeView1.Nodes.Add(wi.WizardName);
                tn.Tag = wi;
            }

        }

        private List<WizardInfo> GetWizards(string path)
        {
            string[] dirs = Directory.GetDirectories(path);
            List<WizardInfo> ret = new List<WizardInfo>();
            string dirname;
            string fname;
            foreach (string dir in dirs)
            {
                dirname = Path.GetFileName(dir);
                fname = Path.Combine(dir, dirname + ".xml");
                if (File.Exists(fname))
                {
                    //try to deserialize
                    try
                    {
                        WizardInfo wi = Util.Deserialize(fname);

                        if (wi != null)
                        {
                            wi.ShortName = dirname;
                            ret.Add(wi);
                        }
                    }
                    catch { }
                }
            }
            return ret;

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            propertyGrid1.SelectedObject = e.Node.Tag;
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode tn = treeView1.Nodes.Add("New");
            tn.Tag = new WizardInfo();

        }


        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = Util.GetWizardDir();
            if (treeView1.SelectedNode != null)
            {

                WizardInfo wi = treeView1.SelectedNode.Tag as WizardInfo;
                string dir = wi.ShortName;
                Util.Serialize(wi, Path.Combine(Path.Combine(path, dir), dir + ".xml"));

            }
        }

        private void importStripMenuItem_Click(object sender, EventArgs e)
        {

            DialogResult dr = folderBrowserDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                string path = folderBrowserDialog1.SelectedPath;
                string[] projfiles = Directory.GetFiles(path, "*.btproj");
                if (projfiles.Length != 0)//found a biztalk project file
                {
                    //copy all the files
                    NameDialog name = new NameDialog();
                    name.Name = Directory.GetParent(path).Name;
                    dr = name.ShowDialog();
                    if (dr == DialogResult.Cancel)
                        return;
                    string wizname = name.Name;
                    string wizdir = Util.GetWizardDir();
                    string newdir = Path.Combine(wizdir, wizname);
                    string vfilesdir = Util.GetVSDirDir();
                    CreateVSDirFiles(wizname, vfilesdir);
                    List<string> filesadded = new List<string>();
                    if (!Directory.Exists(newdir))
                    {
                        DirectoryInfo di = Directory.CreateDirectory(newdir);
                        //create sub dirs
                        string templatesdir = Path.Combine(newdir, "Templates\\1033");
                        Directory.CreateDirectory(templatesdir);
                        //copy the project file
                        string projfile = "BTSApp.btproj";
                        //create new file - remove files and
                        //references
                        XmlDocument d = new XmlDocument();
                        d.Load(projfiles[0]);
                        XmlNode references = d.SelectSingleNode("//References");
                        Dictionary<string, string> lref = new Dictionary<string, string>();
                        foreach (XmlNode cn in references.ChildNodes)
                        {
                            lref.Add(cn.Attributes.GetNamedItem("Name").Value, cn.Attributes.GetNamedItem("AssemblyName").Value);
                            references.RemoveChild(cn);
                        }

                        //File.Copy(projfiles[0], Path.Combine(templatesdir, projfile));
                        //copy the rest of the files
                        foreach (string f in Directory.GetFiles(path, "*.odx"))
                        {
                            File.Copy(f, Path.Combine(templatesdir, Path.GetFileName(f)));
                            filesadded.Add(f);

                        }
                        foreach (string f in Directory.GetFiles(path, "*.btp"))
                        {
                            if (Path.GetExtension(f) != ".btproj")
                            {
                                File.Copy(f, Path.Combine(templatesdir, Path.GetFileName(f)));
                                filesadded.Add(f);
                            }

                        }
                        foreach (string f in Directory.GetFiles(path, "*.xsd"))
                        {
                            File.Copy(f, Path.Combine(templatesdir, Path.GetFileName(f)));
                            filesadded.Add(f);

                        }
                        foreach (string f in Directory.GetFiles(path, "*.btm"))
                        {
                            File.Copy(f, Path.Combine(templatesdir, Path.GetFileName(f)));
                            filesadded.Add(f);

                        }
                        WizardInfo wi = new WizardInfo();
                        foreach (string s in filesadded)
                        {
                            wi.WizardFiles.Add(new WizardFile("BTSProjectWizard.FileGenerators.StaticFileGenerator", Path.GetFileName(s)));

                        }
                        //add references
                        //add files
                        d.Save(Path.Combine(templatesdir, projfile));

                        
                        

                        //add the project file
                        wi.ProjectFile = projfile;
                        wi.WizardName = wizname;
                        Util.Serialize(wi, Path.Combine(newdir, wizname + ".xml"));

                    }


                }
            }
            LoadTree();
        }
     
        private void CreateVSDirFiles(string wizname, string vfilesdir)
        {
            //create the icon
            WizardCreator.Properties.Resources.Test.Save(File.Open(Path.Combine(vfilesdir, wizname + ".ico"), FileMode.Create));
            //create vszFile
            File.WriteAllText(Path.Combine(vfilesdir, wizname + ".vsz"), String.Format(vszFile, wizname));
            //create vsdir file
            File.WriteAllText(Path.Combine(vfilesdir, wizname + ".vsdir"), String.Format(vsdirFile, wizname, "description"));

        }
        void DeleteVSDirFiles(string wizname, string vfilesdir)
        {
            File.Delete(Path.Combine(vfilesdir, wizname + ".vsz"));
            File.Delete(Path.Combine(vfilesdir, wizname + ".vsdir"));

        }
        string vszFile = @"VSWIZARD 7.0
Wizard=BTSProjectWizard.Wizard

Param=""WIZARD_NAME = {0}""
Param=""PROJECT_TYPE = BTPROJ""
Param=""SCRIPT_COMMON_RELATIVE_PATH = {0}
Param=""RELATIVE_PATH = {0}""
Param=""FALLBACK_LCID = 1033""";
        //{0} is short name  - {1} is description"
        string vsdirFile = @"{0}.vsz| |{0}|300|{1}| |6777| |{0}";
        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private void indexToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                string wiz = treeView1.SelectedNode.Text;
                DialogResult dr = MessageBox.Show("Are you sure you want to delete the " + wiz + " wizard?", "Confirm", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.OK)
                {
                    treeView1.Nodes.Remove(treeView1.SelectedNode);
                    DeleteWizard(wiz);
                }
            }

        }

        private void DeleteWizard(string wiz)
        {
            string wizdir = Util.GetWizardDir();
            string newdir = Path.Combine(wizdir, wiz);
            Directory.Delete(newdir, true);//delete the wizard directories
            string vfilesdir = Util.GetVSDirDir();
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender, e);

        }
    }


}